package com.haike.pushjobs.jobs;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.extra.ftp.FtpMode;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.haike.pushjobs.config.GAOLANGANFtpConfig;
import com.haike.pushjobs.service.TPushRecordService;
import com.haike.pushjobs.utils.CSVUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.ibatis.session.SqlSession;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.Pattern;


/**
 * 预报风、降雨、能见度从ftp下载并解析入库
 * /GFS+WRF+ADCIRC+SWAN/WRF_270903/目录下CSV文件: 预报风、降雨、能见度
 */
@Slf4j
@DisallowConcurrentExecution
@Component
public class Download_t_yubao_sml_Job implements Job {

    @Autowired
    SqlSession daoSession;

    @Autowired
    TPushRecordService pushRecordService;

    @Autowired
    private GAOLANGANFtpConfig GAOLANGANFtpConfig;

    String description = "";

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        long funStartTime = System.currentTimeMillis();
        description = context.getJobDetail().getDescription();
        try {
            String param = context.getMergedJobDataMap().getString("param");
            log.info(description + "开始 - 参数: {}", param);

            Map<String, Object> paramMap = JSONUtil.toBean(param, Map.class);

            runTask(paramMap);

        } catch (Exception e) {
            log.error(description + "执行出错", e);
        } finally {
            log.info(description + "执行完成: {} 毫秒", System.currentTimeMillis() - funStartTime);
            log.info("[{}]清除数据源上下文", description);
            DynamicDataSourceContextHolder.clear();
        }
    }


    //region 执行任务

    /**
     * 执行任务
     *
     * @param paramMap
     */
    public void runTask(Map<String, Object> paramMap) {
        String currentDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");


        // FTP服务器配置（使用提供的信息）
        String host = GAOLANGANFtpConfig.getHost();     // FTP服务器主机地址
        int port = GAOLANGANFtpConfig.getPort();        // 端口
        String username = GAOLANGANFtpConfig.getUsername(); // 用户名
        String password = GAOLANGANFtpConfig.getPassword(); // 密码


        // 创建FTP连接配置
        FtpConfig config = new FtpConfig(host, port, username, password, Charset.defaultCharset());
        // 建立FTP连接
        try (Ftp ftp = new Ftp(config, FtpMode.Passive)) {

            var dirList = ftp.lsFiles("/GFS+WRF+ADCIRC+SWAN/WRF_270903/", file -> file.isDirectory());
            if (dirList.size() == 0) {
                log.info("无目录");
                return;
            }
            // dirList进行排序, 降序
            dirList.sort(Comparator.comparing(FTPFile::getName).reversed());

            for (int i = 0; i <= 1; i++) {
                // 只取最新的两个月目录
                FTPFile dir = dirList.get(i);

                // 获取文件名
                String dirName = dir.getName();
                log.info("[目录] " + dirName);

                String remoteDir = "/GFS+WRF+ADCIRC+SWAN/WRF_270903/" + dirName + "/";               // 要列出文件的远程目录，这里使用根目录
                String targetDir = remoteDir.substring(1);
                // 获取当前目录下的所有文件和文件夹列表, 只要.csv文件
                var fileList = ftp.lsFiles(remoteDir, file -> file.getName().endsWith(".csv"));

                log.info("目录 " + remoteDir + " 下的文件列表:");
                for (FTPFile file : fileList) {
                    try {

                        //region 下载文件
                        var fileName = file.getName();
                        if (!FileUtil.exist(targetDir)) {
                            FileUtil.mkdir(targetDir);
                        }
                        String saveFilePath = targetDir + fileName;
                        log.info("保存文件: {}", saveFilePath);

                        if (FileUtil.exist(saveFilePath)) {
                            log.info("[跳过]文件已存在: {}", saveFilePath);
                            continue;
                        }
                        ftp.download(remoteDir + fileName, FileUtil.file(saveFilePath));
                        //endregion

                        //region 插入到数据库
                        // 文件名格式: SML9km_XinHeMaTou_2025081412.csv, 解析出9,XinHeMaTou, 使用正则表达式
                        var matcher = Pattern.compile("^SML(\\d+)km_(.*)_(.*).csv$").matcher(fileName);
                        String type = "";
                        String station_id = "";
                        if (matcher.matches()) {
                            log.info(matcher.group(1));
                            log.info(matcher.group(2));
                            type = matcher.group(1);
                            Date fileDate = DateUtil.parse(matcher.group(3), "yyyyMMddHH");

                            if (fileDate.before(DateUtil.offsetDay(new Date(), -3))) {
                                log.info("超过3天的数据, 跳过");
                                continue;
                            }


                            String stationName = matcher.group(2);
                            if (stationName.equalsIgnoreCase("HaiShiMaTou")) {
                                // 海事码头
                                station_id = "6003";
                            } else if (stationName.equalsIgnoreCase("XinHeMaTou")) {
                                // 鑫和码头
                                station_id = "6007";
                            } else if (stationName.equalsIgnoreCase("GeLiHaiAn")) {
                                // 格力海岸站
                                station_id = "6002";
                            } else if (stationName.equalsIgnoreCase("DF01")) {
                                station_id = "7001";
                            } else if (stationName.equalsIgnoreCase("DF09")) {
                                station_id = "7009";
                            } else if (stationName.equalsIgnoreCase("DF23")) {
                                station_id = "7023";
                            } else if (stationName.equalsIgnoreCase("DF42")) {
                                // 格力海岸站
                                station_id = "7042";
                            }
                        }

                        if (StrUtil.isBlank(station_id)) {
                            log.info("[跳过]无法识别的站点: {}", fileName);
                            continue;
                        }

                        var list = CSVUtils.parseCSV(saveFilePath);
                        for (var item : list) {
                            log.info("[{}]开始推送数据: {}", description, item);
                            item.put("id", IdUtil.getSnowflakeNextId());
                            item.put("station_id", station_id);
                            item.put("type", type);
//            item.put("data_time",DateUtil.parse(item.get("time").toString()));
                            item.put("data_time", item.get("time"));
                            daoSession.insert("data.insert_t_yubao_sml", item);
                        }
                        //endregion


                    } catch (Exception e) {
                        log.error("下载文件出错: {}", e.getMessage());
                    }
                }
            }


        } catch (Exception e) {
            log.error("FTP操作出错: " + e.getMessage(), e);
        }


    }
    //endregion


    public static void main(String[] args) {

        Date date = DateUtil.parse("2025082212", "yyyyMMddHH");
        // date> 现在时间 -10天

        System.out.println(DateUtil.offsetDay(new Date(), -10));

        System.out.println(date);


        // FTP服务器配置（使用提供的信息）
//        String host = "www.hellosea.org.cn";  // FTP服务器主机地址
//        int port = 10021;                     // 端口
//        String username = "2K93940";          // 用户名
//        String password = "P773032";          // 密码
//        String remoteDir = "/GFS+WRF+ADCIRC+SWAN/WRF_270903/" + DateUtil.format(new Date(), "yyyyMM") + "/";               // 要列出文件的远程目录，这里使用根目录
//        String targetDir = remoteDir.substring(1);
//
//        log.info(DateUtil.format(new Date(), "yyyyMM"));
//        // 创建FTP连接配置
//        FtpConfig config = new FtpConfig(host, port, username, password, Charset.defaultCharset());
//
//
//        // 建立FTP连接
//        try (Ftp ftp = new Ftp(config, FtpMode.Passive)) {
//            // 获取当前目录下的所有文件和文件夹列表, 只要.csv文件
//            var fileList = ftp.lsFiles(remoteDir, file -> file.getName().endsWith(".csv"));
//
//            log.info("目录 " + remoteDir + " 下的文件列表:");
//            for (FTPFile file : fileList) {
//                // 判断是文件还是目录
//                if (file.isDirectory()) {
//                    log.info("[目录] " + file.getName());
//                } else {
//                    log.info("[文件] " + file.getName());
//                }
//                // 文件名格式: SML9km_XinHeMaTou_2025081412.csv, 解析出9,XinHeMaTou, 使用正则表达式
//                var fileName = file.getName();
//                if (!FileUtil.exist(targetDir)) {
//                    FileUtil.mkdir(targetDir);
//                }
//                if (FileUtil.exist(targetDir + fileName)) {
//                    continue;
//                }
//                ftp.download(remoteDir + fileName, FileUtil.file(targetDir + fileName));
//                var matcher = Pattern.compile("^SML(\\d+)km_(.*)_(.*).csv$").matcher(fileName);
//                if (matcher.matches()) {
//                    log.info(matcher.group(1));
//                    log.info(matcher.group(2));
//                }
//
//
//            }
//
//        } catch (Exception e) {
//            System.err.println("FTP操作出错: " + e.getMessage());
//            e.printStackTrace();
//        }
    }


    public static void main11(String[] args) {
        CsvReadConfig config = CsvReadConfig.defaultConfig();
        config.setContainsHeader(true);

        var reader = CsvUtil.getReader(config);
        String file_path = "C:\\Users\\45363\\Desktop\\SML3km_HaiShiMaTou_2025080112.csv";
        CsvData csvData = reader.read(FileUtil.file(file_path), CharsetUtil.CHARSET_UTF_8);

        // 将 CSV 数据转换为 List<Map<String, Object>>
        List<Map<String, Object>> result_list = new ArrayList<>();
        var header = csvData.getHeader();
        for (List<String> row : csvData.getRows()) {
            Map<String, Object> row_map = new HashMap<>();
            for (int i = 0; i < header.size(); i++) {
                String key = header.get(i);
                // key是格式是 Rain(mm).  去掉 ()
                key = key.replaceAll("\\(.*\\)", "").trim().toLowerCase();

                String value = row.get(i);
                row_map.put(key, value);
            }
            result_list.add(row_map);
        }

    }
}